import axios, { AxiosError, AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import { wrapperToken, wrapperEnv } from '@/utils'
// 格式化import.meta.env对象格式
const viteEnv = wrapperEnv(import.meta.env)

const { VITE_BASE_API, VITE_REQUEST_TIMEOUT, VITE_TOKEN_STR } = viteEnv

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: VITE_BASE_API,
  timeout: VITE_REQUEST_TIMEOUT
})
// axios 请求拦截
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = wrapperToken.getToken()
    if (token) {
      config.headers[VITE_TOKEN_STR] = token
    }
    return config
  },
  (error: AxiosError) => {
    ElMessage.error(error)
    Promise.reject(error)
  }
)
// axios 响应拦截
service.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    const { data } = response
    if (data.code !== 0) {
      ElMessage.error(data.msg || data.message || 'error')
      // 身份认证失败 移除token 重新加载页面
      if (data.code === 401) {
        // wrapperToken.removeToken()
        // setTimeout(() => {
        //   location.reload()
        // }, 2000)
      }
    } else {
      return data
    }
  },
  error => {
    return Promise.reject(error)
  }
)
export default service
